package com.api;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;

import com.bean.UnifiedorderResult;
import com.utils.LocalHttpClient;
import com.utils.SignatureUtil;
import com.utils.XmlUtils;


/**
 * 微信支付 基于V3.X 版本
 *
 * @author Yi
 */
public class PayMchAPI extends BaseAPI {


    /**
     * 统一下单
     *
     * @param unifiedorder
     * @param key
     * @return
     */
    public static UnifiedorderResult payUnifiedorder(Map unifiedorder, String key) {
        if (key != null) {
            String sign = SignatureUtil.generateSign(unifiedorder, key);
            unifiedorder.put("sign", sign);
        }
        String unifiedorderXML = XmlUtils.toXml(unifiedorder);
        System.out.println("参数:" + unifiedorderXML);
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(xmlHeader)
                .setUri(MCH_URI + "/pay/unifiedorder")
                .setEntity(new StringEntity(unifiedorderXML, Charset.forName("utf-8")))
                .build();
        return LocalHttpClient.executeXmlResult(httpUriRequest, UnifiedorderResult.class);
    }

    public static InputStream payInputStream(Map param, String key) throws IOException {
        if (key != null) {
            String sign = SignatureUtil.generateSign(param, key);
            param.put("sign", sign);
        }
        String unifiedorderXML = XmlUtils.toXml(param);
        System.out.println("参数:" + unifiedorderXML);
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(xmlHeader)
                .setUri(MCH_URI + "/pay/unifiedorder")
                .setEntity(new StringEntity(unifiedorderXML, Charset.forName("utf-8")))
                .build();
        HttpResponse result = LocalHttpClient.execute(httpUriRequest);
        return result.getEntity().getContent();
    }
}
